package com.study.suanfa.shuzu;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @description: xssz    稀疏数组   压缩二位数组
 * @date: 2020/11/27 16:49
 * @author: hcm
 * @version: 1.0
 */
public class xssz {
    public static void main(String[] args) {

        //定义二维数组
        int[][] arr = new int[11][11];
        arr[1][2] = 1;
        arr[2][3] = 2;
        for (int[] ints : arr) {
            for (int anInt : ints) {
                System.out.print(anInt + " ");
            }
            System.out.println();
        }

        //遍历，得到非0数据个数
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int i1 = 0; i1 < 11; i1++) {
                if (arr[i][i1] != 0) {
                    sum++;
                }
            }
        }
        System.out.println(sum);
        //创建稀疏数组
        int[][] xsArr = new int[sum + 1][3];
        //赋值
        xsArr[0][0] = 11;
        xsArr[0][1] = 11;
        xsArr[0][2] = sum;

        //记录第几个非0数据
        int count = 0;
        //遍历，将非0存到稀疏数组中
        for (int i = 0; i < 11; i++) {

            for (int j = 0; j < 11; j++) {

                if (arr[i][j] != 0) {
                    count++;
                    xsArr[count][0] = i;
                    xsArr[count][1] = j;
                    xsArr[count][2] = arr[i][j];
                }
            }
        }
        System.out.println();
        System.out.println("稀疏数组：");
        for (int i = 0; i < xsArr.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n", xsArr[i][0], xsArr[i][1], xsArr[i][2]);
        }

        //还原数组
        int[][] reArr = new int[xsArr[0][0]][xsArr[0][1]];
        for (int i = 1; i < xsArr.length; i++) {
            reArr[xsArr[i][0]][xsArr[i][1]] = xsArr[i][2];
        }
        for (int i = 0; i < reArr.length; i++) {

            for (int j = 0; j < reArr.length; j++) {

                System.out.print(reArr[i][j]+" ");
            }
            System.out.println();
        }
    }
}
